home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / doc / python / faq / extending.html next >
Encoding:
Extensible Markup Language  |  2009-04-19  |  34.4 KB  |  740 lines

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta name="generator" content="Docutils 0.5: http://docutils.sourceforge.net/" />
  7. <title>Extending/Embedding FAQ</title>
  8. <meta name="date" content="2004-04-08" />
  9. <style type="text/css">
  10.  
  11. /*
  12. :Author: David Goodger (goodger@python.org)
  13. :Id: $Id: html4css1.css 5196 2007-06-03 20:25:28Z wiemann $
  14. :Copyright: This stylesheet has been placed in the public domain.
  15.  
  16. Default cascading style sheet for the HTML output of Docutils.
  17.  
  18. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
  19. customize this style sheet.
  20. */
  21.  
  22. /* used to remove borders from tables and images */
  23. .borderless, table.borderless td, table.borderless th {
  24.   border: 0 }
  25.  
  26. table.borderless td, table.borderless th {
  27.   /* Override padding for "table.docutils td" with "! important".
  28.      The right padding separates the table cells. */
  29.   padding: 0 0.5em 0 0 ! important }
  30.  
  31. .first {
  32.   /* Override more specific margin styles with "! important". */
  33.   margin-top: 0 ! important }
  34.  
  35. .last, .with-subtitle {
  36.   margin-bottom: 0 ! important }
  37.  
  38. .hidden {
  39.   display: none }
  40.  
  41. a.toc-backref {
  42.   text-decoration: none ;
  43.   color: black }
  44.  
  45. blockquote.epigraph {
  46.   margin: 2em 5em ; }
  47.  
  48. dl.docutils dd {
  49.   margin-bottom: 0.5em }
  50.  
  51. /* Uncomment (and remove this text!) to get bold-faced definition list terms
  52. dl.docutils dt {
  53.   font-weight: bold }
  54. */
  55.  
  56. div.abstract {
  57.   margin: 2em 5em }
  58.  
  59. div.abstract p.topic-title {
  60.   font-weight: bold ;
  61.   text-align: center }
  62.  
  63. div.admonition, div.attention, div.caution, div.danger, div.error,
  64. div.hint, div.important, div.note, div.tip, div.warning {
  65.   margin: 2em ;
  66.   border: medium outset ;
  67.   padding: 1em }
  68.  
  69. div.admonition p.admonition-title, div.hint p.admonition-title,
  70. div.important p.admonition-title, div.note p.admonition-title,
  71. div.tip p.admonition-title {
  72.   font-weight: bold ;
  73.   font-family: sans-serif }
  74.  
  75. div.attention p.admonition-title, div.caution p.admonition-title,
  76. div.danger p.admonition-title, div.error p.admonition-title,
  77. div.warning p.admonition-title {
  78.   color: red ;
  79.   font-weight: bold ;
  80.   font-family: sans-serif }
  81.  
  82. /* Uncomment (and remove this text!) to get reduced vertical space in
  83.    compound paragraphs.
  84. div.compound .compound-first, div.compound .compound-middle {
  85.   margin-bottom: 0.5em }
  86.  
  87. div.compound .compound-last, div.compound .compound-middle {
  88.   margin-top: 0.5em }
  89. */
  90.  
  91. div.dedication {
  92.   margin: 2em 5em ;
  93.   text-align: center ;
  94.   font-style: italic }
  95.  
  96. div.dedication p.topic-title {
  97.   font-weight: bold ;
  98.   font-style: normal }
  99.  
  100. div.figure {
  101.   margin-left: 2em ;
  102.   margin-right: 2em }
  103.  
  104. div.footer, div.header {
  105.   clear: both;
  106.   font-size: smaller }
  107.  
  108. div.line-block {
  109.   display: block ;
  110.   margin-top: 1em ;
  111.   margin-bottom: 1em }
  112.  
  113. div.line-block div.line-block {
  114.   margin-top: 0 ;
  115.   margin-bottom: 0 ;
  116.   margin-left: 1.5em }
  117.  
  118. div.sidebar {
  119.   margin: 0 0 0.5em 1em ;
  120.   border: medium outset ;
  121.   padding: 1em ;
  122.   background-color: #ffffee ;
  123.   width: 40% ;
  124.   float: right ;
  125.   clear: right }
  126.  
  127. div.sidebar p.rubric {
  128.   font-family: sans-serif ;
  129.   font-size: medium }
  130.  
  131. div.system-messages {
  132.   margin: 5em }
  133.  
  134. div.system-messages h1 {
  135.   color: red }
  136.  
  137. div.system-message {
  138.   border: medium outset ;
  139.   padding: 1em }
  140.  
  141. div.system-message p.system-message-title {
  142.   color: red ;
  143.   font-weight: bold }
  144.  
  145. div.topic {
  146.   margin: 2em }
  147.  
  148. h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
  149. h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
  150.   margin-top: 0.4em }
  151.  
  152. h1.title {
  153.   text-align: center }
  154.  
  155. h2.subtitle {
  156.   text-align: center }
  157.  
  158. hr.docutils {
  159.   width: 75% }
  160.  
  161. img.align-left {
  162.   clear: left }
  163.  
  164. img.align-right {
  165.   clear: right }
  166.  
  167. ol.simple, ul.simple {
  168.   margin-bottom: 1em }
  169.  
  170. ol.arabic {
  171.   list-style: decimal }
  172.  
  173. ol.loweralpha {
  174.   list-style: lower-alpha }
  175.  
  176. ol.upperalpha {
  177.   list-style: upper-alpha }
  178.  
  179. ol.lowerroman {
  180.   list-style: lower-roman }
  181.  
  182. ol.upperroman {
  183.   list-style: upper-roman }
  184.  
  185. p.attribution {
  186.   text-align: right ;
  187.   margin-left: 50% }
  188.  
  189. p.caption {
  190.   font-style: italic }
  191.  
  192. p.credits {
  193.   font-style: italic ;
  194.   font-size: smaller }
  195.  
  196. p.label {
  197.   white-space: nowrap }
  198.  
  199. p.rubric {
  200.   font-weight: bold ;
  201.   font-size: larger ;
  202.   color: maroon ;
  203.   text-align: center }
  204.  
  205. p.sidebar-title {
  206.   font-family: sans-serif ;
  207.   font-weight: bold ;
  208.   font-size: larger }
  209.  
  210. p.sidebar-subtitle {
  211.   font-family: sans-serif ;
  212.   font-weight: bold }
  213.  
  214. p.topic-title {
  215.   font-weight: bold }
  216.  
  217. pre.address {
  218.   margin-bottom: 0 ;
  219.   margin-top: 0 ;
  220.   font-family: serif ;
  221.   font-size: 100% }
  222.  
  223. pre.literal-block, pre.doctest-block {
  224.   margin-left: 2em ;
  225.   margin-right: 2em }
  226.  
  227. span.classifier {
  228.   font-family: sans-serif ;
  229.   font-style: oblique }
  230.  
  231. span.classifier-delimiter {
  232.   font-family: sans-serif ;
  233.   font-weight: bold }
  234.  
  235. span.interpreted {
  236.   font-family: sans-serif }
  237.  
  238. span.option {
  239.   white-space: nowrap }
  240.  
  241. span.pre {
  242.   white-space: pre }
  243.  
  244. span.problematic {
  245.   color: red }
  246.  
  247. span.section-subtitle {
  248.   /* font-size relative to parent (h1..h6 element) */
  249.   font-size: 80% }
  250.  
  251. table.citation {
  252.   border-left: solid 1px gray;
  253.   margin-left: 1px }
  254.  
  255. table.docinfo {
  256.   margin: 2em 4em }
  257.  
  258. table.docutils {
  259.   margin-top: 0.5em ;
  260.   margin-bottom: 0.5em }
  261.  
  262. table.footnote {
  263.   border-left: solid 1px black;
  264.   margin-left: 1px }
  265.  
  266. table.docutils td, table.docutils th,
  267. table.docinfo td, table.docinfo th {
  268.   padding-left: 0.5em ;
  269.   padding-right: 0.5em ;
  270.   vertical-align: top }
  271.  
  272. table.docutils th.field-name, table.docinfo th.docinfo-name {
  273.   font-weight: bold ;
  274.   text-align: left ;
  275.   white-space: nowrap ;
  276.   padding-left: 0 }
  277.  
  278. h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
  279. h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
  280.   font-size: 100% }
  281.  
  282. ul.auto-toc {
  283.   list-style-type: none }
  284.  
  285. </style>
  286. </head>
  287. <body>
  288. <div class="document" id="extending-embedding-faq">
  289. <h1 class="title">Extending/Embedding FAQ</h1>
  290. <table class="docinfo" frame="void" rules="none">
  291. <col class="docinfo-name" />
  292. <col class="docinfo-content" />
  293. <tbody valign="top">
  294. <tr><th class="docinfo-name">Date:</th>
  295. <td>2004-04-08</td></tr>
  296. <tr><th class="docinfo-name">Version:</th>
  297. <td>7294</td></tr>
  298. <tr class="field"><th class="docinfo-name">Web site:</th><td class="field-body"><a class="reference external" href="http://www.python.org/">http://www.python.org/</a></td>
  299. </tr>
  300. </tbody>
  301. </table>
  302. <div class="contents topic" id="contents">
  303. <p class="topic-title first">Contents</p>
  304. <ul class="auto-toc simple">
  305. <li><a class="reference internal" href="#can-i-create-my-own-functions-in-c" id="id7">1   Can I create my own functions in C?</a></li>
  306. <li><a class="reference internal" href="#id1" id="id8">2   Can I create my own functions in C++?</a></li>
  307. <li><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives" id="id9">3   Writing C is hard; are there any alternatives?</a></li>
  308. <li><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c" id="id10">4   How can I execute arbitrary Python statements from C?</a></li>
  309. <li><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" id="id11">5   How can I evaluate an arbitrary Python expression from C?</a></li>
  310. <li><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object" id="id12">6   How do I extract C values from a Python object?</a></li>
  311. <li><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" id="id13">7   How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
  312. <li><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c" id="id14">8   How do I call an object's method from C?</a></li>
  313. <li><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" id="id15">9   How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
  314. <li><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c" id="id16">10   How do I access a module written in Python from C?</a></li>
  315. <li><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python" id="id17">11   How do I interface to C++ objects from Python?</a></li>
  316. <li><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" id="id18">12   I added a module using the Setup file and the make fails; why?</a></li>
  317. <li><a class="reference internal" href="#how-do-i-debug-an-extension" id="id19">13   How do I debug an extension?</a></li>
  318. <li><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" id="id20">14   I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
  319. <li><a class="reference internal" href="#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean" id="id21">15   What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?</a></li>
  320. <li><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input" id="id22">16   How do I tell "incomplete input" from "invalid input"?</a></li>
  321. <li><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" id="id23">17   How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
  322. <li><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" id="id24">18   Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
  323. <li><a class="reference internal" href="#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2" id="id25">19   When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"?</a></li>
  324. </ul>
  325. </div>
  326. <div class="section" id="can-i-create-my-own-functions-in-c">
  327. <h1><a class="toc-backref" href="#id7">1   Can I create my own functions in C?</a></h1>
  328. <p>Yes, you can create built-in modules containing functions,
  329. variables, exceptions and even new types in C.  This is explained in
  330. the document "Extending and Embedding the Python Interpreter" (<a class="reference external" href="http://docs.python.org/ext/ext.html">http://docs.python.org/ext/ext.html</a>).</p>
  331. <p>Most intermediate or advanced Python books will also
  332. cover this topic.</p>
  333. </div>
  334. <div class="section" id="id1">
  335. <h1><a class="toc-backref" href="#id8">2   Can I create my own functions in C++?</a></h1>
  336. <p>Yes, using the C compatibility features found in C++.
  337. Place <tt class="docutils literal"><span class="pre">extern</span> <span class="pre">"C"</span> <span class="pre">{</span> <span class="pre">...</span> <span class="pre">}</span></tt> around the Python include files and put
  338. <tt class="docutils literal"><span class="pre">extern</span> <span class="pre">"C"</span></tt> before each function that is going to be called by the
  339. Python interpreter.  Global or static C++ objects with constructors
  340. are probably not a good idea.</p>
  341. </div>
  342. <div class="section" id="writing-c-is-hard-are-there-any-alternatives">
  343. <h1><a class="toc-backref" href="#id9">3   Writing C is hard; are there any alternatives?</a></h1>
  344. <p>There are a number of alternatives to writing your own C extensions,
  345. depending on what you're trying to do.</p>
  346. <p>If you need more speed, <a class="reference external" href="http://psyco.sourceforge.net/">Psyco</a> generates x86 assembly code
  347. from Python bytecode.  You can use Psyco to compile the most
  348. time-critical functions in your code, and gain a significant
  349. improvement with very little effort, as long as you're running on a
  350. machine with an x86-compatible processor.</p>
  351. <p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> is a compiler that accepts a slightly modified form of Python
  352. and generates the corresponding C code.  Pyrex makes it possible to write
  353. an extension without having to learn Python's C API.</p>
  354. <p>If you need to interface to some C library for which no Python
  355. extension currently exists, you can try wrapping the library's data
  356. types and functions with a tool such as <a class="reference external" href="http://www.swig.org">SWIG</a>.
  357. For C++ libraries, you can look at <a class="reference external" href="http://www.riverbankcomputing.co.uk/sip/">SIP</a>, <a class="reference external" href="http://cxx.sourceforge.net/">CXX</a>, <a class="reference external" href="http://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference external" href="http://www.scipy.org/site_content/weave">Weave</a>.</p>
  358. </div>
  359. <div class="section" id="how-can-i-execute-arbitrary-python-statements-from-c">
  360. <h1><a class="toc-backref" href="#id10">4   How can I execute arbitrary Python statements from C?</a></h1>
  361. <p>The highest-level function to do this is <tt class="docutils literal"><span class="pre">PyRun_SimpleString()</span></tt> which takes
  362. a single string argument to be executed in the context of the module
  363. <tt class="docutils literal"><span class="pre">__main__</span></tt> and returns 0 for success and -1 when an exception occurred
  364. (including <tt class="docutils literal"><span class="pre">SyntaxError</span></tt>).  If you want more control, use <tt class="docutils literal"><span class="pre">PyRun_String()</span></tt>;
  365. see the source for <tt class="docutils literal"><span class="pre">PyRun_SimpleString()</span></tt> in Python/pythonrun.c.</p>
  366. </div>
  367. <div class="section" id="how-can-i-evaluate-an-arbitrary-python-expression-from-c">
  368. <h1><a class="toc-backref" href="#id11">5   How can I evaluate an arbitrary Python expression from C?</a></h1>
  369. <p>Call the function <tt class="docutils literal"><span class="pre">PyRun_String()</span></tt> from the previous question with the
  370. start symbol <tt class="docutils literal"><span class="pre">Py_eval_input</span></tt>; it
  371. parses an expression, evaluates it and returns its value.</p>
  372. </div>
  373. <div class="section" id="how-do-i-extract-c-values-from-a-python-object">
  374. <h1><a class="toc-backref" href="#id12">6   How do I extract C values from a Python object?</a></h1>
  375. <p>That depends on the object's type.  If it's a tuple,
  376. <tt class="docutils literal"><span class="pre">PyTupleSize(o)</span></tt> returns its length and <tt class="docutils literal"><span class="pre">PyTuple_GetItem(o,</span> <span class="pre">i)</span></tt>
  377. returns its i'th item.  Lists have similar functions, <tt class="docutils literal"><span class="pre">PyListSize(o)</span></tt>
  378. and <tt class="docutils literal"><span class="pre">PyList_GetItem(o,</span> <span class="pre">i)</span></tt>.</p>
  379. <p>For strings, <tt class="docutils literal"><span class="pre">PyString_Size(o)</span></tt> returns
  380. its length and <tt class="docutils literal"><span class="pre">PyString_AsString(o)</span></tt> a pointer to its value.
  381. Note that Python strings may contain null bytes so C's <tt class="docutils literal"><span class="pre">strlen()</span></tt>
  382. should not be used.</p>
  383. <p>To test the type of an object, first make sure
  384. it isn't NULL, and then use <tt class="docutils literal"><span class="pre">PyString_Check(o)</span></tt>, <tt class="docutils literal"><span class="pre">PyTuple_Check(o)</span></tt>,
  385. <tt class="docutils literal"><span class="pre">PyList_Check(o)</span></tt>, etc.</p>
  386. <p>There is also a high-level API to Python objects which is
  387. provided by the so-called 'abstract' interface -- read
  388. <tt class="docutils literal"><span class="pre">Include/abstract.h</span></tt> for further details.  It allows
  389. interfacing with any kind of Python sequence
  390. using calls like <tt class="docutils literal"><span class="pre">PySequence_Length()</span></tt>, <tt class="docutils literal"><span class="pre">PySequence_GetItem()</span></tt>, etc.)
  391. as well as many other useful protocols.</p>
  392. </div>
  393. <div class="section" id="how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">
  394. <h1><a class="toc-backref" href="#id13">7   How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></h1>
  395. <p>You can't.  Use <tt class="docutils literal"><span class="pre">t</span> <span class="pre">=</span> <span class="pre">PyTuple_New(n)</span></tt> instead, and fill it with
  396. objects using <tt class="docutils literal"><span class="pre">PyTuple_SetItem(t,</span> <span class="pre">i,</span> <span class="pre">o)</span></tt> -- note that this "eats" a
  397. reference count of <tt class="docutils literal"><span class="pre">o</span></tt>, so you have to <tt class="docutils literal"><span class="pre">Py_INCREF</span></tt> it.
  398. Lists have similar functions <tt class="docutils literal"><span class="pre">PyList_New(n)</span></tt> and
  399. <tt class="docutils literal"><span class="pre">PyList_SetItem(l,</span> <span class="pre">i,</span> <span class="pre">o)</span></tt>.  Note that you <em>must</em> set all the tuple items to
  400. some value before you pass the tuple to Python code --
  401. <tt class="docutils literal"><span class="pre">PyTuple_New(n)</span></tt> initializes them to NULL, which isn't a valid Python
  402. value.</p>
  403. </div>
  404. <div class="section" id="how-do-i-call-an-object-s-method-from-c">
  405. <h1><a class="toc-backref" href="#id14">8   How do I call an object's method from C?</a></h1>
  406. <p>The <tt class="docutils literal"><span class="pre">PyObject_CallMethod()</span></tt> function can be used to call an arbitrary
  407. method of an object.  The parameters are the object, the name of the
  408. method to call, a format string like that used with <tt class="docutils literal"><span class="pre">Py_BuildValue()</span></tt>, and the argument values:</p>
  409. <pre class="literal-block">
  410. PyObject *
  411. PyObject_CallMethod(PyObject *object, char *method_name,
  412.                     char *arg_format, ...);
  413. </pre>
  414. <p>This works for any object that has methods -- whether built-in or
  415. user-defined.  You are responsible for eventually <tt class="docutils literal"><span class="pre">Py_DECREF</span></tt>'ing the
  416. return value.</p>
  417. <p>To call, e.g., a file object's "seek" method with arguments 10, 0
  418. (assuming the file object pointer is "f"):</p>
  419. <pre class="literal-block">
  420. res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
  421. if (res == NULL) {
  422.         ... an exception occurred ...
  423. }
  424. else {
  425.         Py_DECREF(res);
  426. }
  427. </pre>
  428. <p>Note that since <tt class="docutils literal"><span class="pre">PyObject_CallObject()</span></tt> <em>always</em> wants a tuple for the
  429. argument list, to call a function without arguments, pass "()" for the
  430. format, and to call a function with one argument, surround the argument
  431. in parentheses, e.g. "(i)".</p>
  432. </div>
  433. <div class="section" id="how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">
  434. <h1><a class="toc-backref" href="#id15">9   How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></h1>
  435. <p>In Python code, define an object that supports the <tt class="docutils literal"><span class="pre">write()</span></tt> method.
  436. Assign this object to <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> and <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>.
  437. Call print_error, or just allow the standard traceback mechanism to
  438. work. Then, the output will go wherever your <tt class="docutils literal"><span class="pre">write()</span></tt> method sends it.</p>
  439. <p>The easiest way to do this is to use the StringIO class in the standard
  440. library.</p>
  441. <p>Sample code and use for catching stdout:</p>
  442. <pre class="literal-block">
  443. >>> class StdoutCatcher:
  444. ...     def __init__(self):
  445. ...         self.data = ''
  446. ...     def write(self, stuff):
  447. ...         self.data = self.data + stuff
  448. ...
  449. >>> import sys
  450. >>> sys.stdout = StdoutCatcher()
  451. >>> print 'foo'
  452. >>> print 'hello world!'
  453. >>> sys.stderr.write(sys.stdout.data)
  454. foo
  455. hello world!
  456. </pre>
  457. </div>
  458. <div class="section" id="how-do-i-access-a-module-written-in-python-from-c">
  459. <h1><a class="toc-backref" href="#id16">10   How do I access a module written in Python from C?</a></h1>
  460. <p>You can get a pointer to the module object as follows:</p>
  461. <pre class="literal-block">
  462. module = PyImport_ImportModule("<modulename>");
  463. </pre>
  464. <p>If the module hasn't been imported yet (i.e. it is not yet present in
  465. <tt class="docutils literal"><span class="pre">sys.modules</span></tt>), this initializes the module; otherwise it simply returns
  466. the value of <tt class="docutils literal"><span class="pre">sys.modules["<modulename>"]</span></tt>.  Note that it doesn't enter
  467. the module into any namespace -- it only ensures it has been
  468. initialized and is stored in <tt class="docutils literal"><span class="pre">sys.modules</span></tt>.</p>
  469. <p>You can then access the module's attributes (i.e. any name defined in
  470. the module) as follows:</p>
  471. <pre class="literal-block">
  472. attr = PyObject_GetAttrString(module, "<attrname>");
  473. </pre>
  474. <p>Calling <tt class="docutils literal"><span class="pre">PyObject_SetAttrString()</span></tt> to assign to variables in the module also works.</p>
  475. </div>
  476. <div class="section" id="how-do-i-interface-to-c-objects-from-python">
  477. <h1><a class="toc-backref" href="#id17">11   How do I interface to C++ objects from Python?</a></h1>
  478. <p>Depending on your requirements, there are many approaches.  To do
  479. this manually, begin by reading <a class="reference external" href="http://docs.python.org/ext/ext.html">the "Extending and Embedding" document</a>.  Realize
  480. that for the Python run-time system, there isn't a whole lot of
  481. difference between C and C++ -- so the strategy of building a new Python
  482. type around a C structure (pointer) type will also work for C++
  483. objects.</p>
  484. <p>For C++ libraries, you can look at <a class="reference external" href="http://www.riverbankcomputing.co.uk/sip/">SIP</a>, <a class="reference external" href="http://cxx.sourceforge.net/">CXX</a>, <a class="reference external" href="http://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference external" href="http://www.scipy.org/site_content/weave">Weave</a>.
  485. <a class="reference external" href="http://www.swig.org">SWIG</a> is a similar automated tool that only supports C libraries.</p>
  486. </div>
  487. <div class="section" id="i-added-a-module-using-the-setup-file-and-the-make-fails-why">
  488. <h1><a class="toc-backref" href="#id18">12   I added a module using the Setup file and the make fails; why?</a></h1>
  489. <p>Setup must end in a newline, if there is no newline there, the build
  490. process fails.  (Fixing this requires some ugly shell script hackery,
  491. and this bug is so minor that it doesn't seem worth the effort.)</p>
  492. </div>
  493. <div class="section" id="how-do-i-debug-an-extension">
  494. <h1><a class="toc-backref" href="#id19">13   How do I debug an extension?</a></h1>
  495. <p>When using GDB with dynamically loaded extensions, you can't set a
  496. breakpoint in your extension until your extension is loaded.</p>
  497. <p>In your <tt class="docutils literal"><span class="pre">.gdbinit</span></tt> file (or interactively), add the command:</p>
  498. <pre class="literal-block">
  499. br _PyImport_LoadDynamicModule
  500. </pre>
  501. <p>Then, when you run GDB:</p>
  502. <pre class="literal-block">
  503. $ gdb /local/bin/python
  504. gdb) run myscript.py
  505. gdb) continue # repeat until your extension is loaded
  506. gdb) finish   # so that your extension is loaded
  507. gdb) br myfunction.c:50
  508. gdb) continue
  509. </pre>
  510. </div>
  511. <div class="section" id="i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">
  512. <h1><a class="toc-backref" href="#id20">14   I want to compile a Python module on my Linux system, but some files are missing. Why?</a></h1>
  513. <p>Most packaged versions of Python don't include the
  514. /usr/lib/python2.x/config/ directory, which contains various files required
  515. for compiling Python extensions.</p>
  516. <p>For Red Hat, install the python-devel RPM to get the necessary files.</p>
  517. <p>For Debian, run <tt class="docutils literal"><span class="pre">apt-get</span> <span class="pre">install</span> <span class="pre">python-dev</span></tt>.</p>
  518. </div>
  519. <div class="section" id="what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean">
  520. <h1><a class="toc-backref" href="#id21">15   What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?</a></h1>
  521. <p>This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name.</p>
  522. <p>Every module init function will have a line similar to:</p>
  523. <pre class="literal-block">
  524. module = Py_InitModule("yourmodule", yourmodule_functions);
  525. </pre>
  526. <p>If the string passed to this function is not the same name as your
  527. extenion module, the <tt class="docutils literal"><span class="pre">SystemError</span></tt> exception will be raised.</p>
  528. </div>
  529. <div class="section" id="how-do-i-tell-incomplete-input-from-invalid-input">
  530. <h1><a class="toc-backref" href="#id22">16   How do I tell "incomplete input" from "invalid input"?</a></h1>
  531. <p>Sometimes you want to emulate the Python interactive interpreter's
  532. behavior, where it gives you a continuation prompt when the input
  533. is incomplete (e.g. you typed the start of an "if" statement
  534. or you didn't close your parentheses or triple string quotes),
  535. but it gives you a syntax error message immediately when the input
  536. is invalid.</p>
  537. <p>In Python you can use the <tt class="docutils literal"><span class="pre">codeop</span></tt> module, which approximates the
  538. parser's behavior sufficiently.  IDLE uses this, for example.</p>
  539. <p>The easiest way to do it in C is to call <tt class="docutils literal"><span class="pre">PyRun_InteractiveLoop()</span></tt>
  540. (perhaps in a separate thread) and let the Python interpreter handle
  541. the input for you. You can also set the <tt class="docutils literal"><span class="pre">PyOS_ReadlineFunctionPointer</span></tt>
  542. to point at your custom input function. See <tt class="docutils literal"><span class="pre">Modules/readline.c</span></tt> and
  543. <tt class="docutils literal"><span class="pre">Parser/myreadline.c</span></tt> for more hints.</p>
  544. <p>However sometimes you have to run the embedded Python interpreter in
  545. the same thread as your rest application and you can't allow the
  546. <tt class="docutils literal"><span class="pre">PyRun_InteractiveLoop()</span></tt> to stop while waiting for user input.  The
  547. one solution then is to call <tt class="docutils literal"><span class="pre">PyParser_ParseString()</span></tt> and test for
  548. <tt class="docutils literal"><span class="pre">e.error</span></tt> equal to <tt class="docutils literal"><span class="pre">E_EOF</span></tt>, which means the input is incomplete).
  549. Here's a sample code fragment, untested, inspired by code from Alex Farber:</p>
  550. <pre class="literal-block">
  551. #include <Python.h>
  552. #include <node.h>
  553. #include <errcode.h>
  554. #include <grammar.h>
  555. #include <parsetok.h>
  556. #include <compile.h>
  557.  
  558. int testcomplete(char *code)
  559.   /* code should end in \n */
  560.   /* return -1 for error, 0 for incomplete, 1 for complete */
  561. {
  562.   node *n;
  563.   perrdetail e;
  564.  
  565.   n = PyParser_ParseString(code, &_PyParser_Grammar,
  566.                            Py_file_input, &e);
  567.   if (n == NULL) {
  568.     if (e.error == E_EOF)
  569.       return 0;
  570.     return -1;
  571.   }
  572.  
  573.   PyNode_Free(n);
  574.   return 1;
  575. }
  576. </pre>
  577. <p>Another solution is trying to compile the received string with
  578. <tt class="docutils literal"><span class="pre">Py_CompileString()</span></tt>. If it compiles without errors, try to execute the returned
  579. code object by calling <tt class="docutils literal"><span class="pre">PyEval_EvalCode()</span></tt>. Otherwise save the input for
  580. later. If the compilation fails, find out if it's an error or just
  581. more input is required - by extracting the message string from the
  582. exception tuple and comparing it to the string "unexpected EOF while parsing".
  583. Here is a complete example using the GNU readline library (you may
  584. want to ignore SIGINT while calling readline()):</p>
  585. <pre class="literal-block">
  586. #include <stdio.h>
  587. #include <readline.h>
  588.  
  589. #include <Python.h>
  590. #include <object.h>
  591. #include <compile.h>
  592. #include <eval.h>
  593.  
  594. int main (int argc, char* argv[])
  595. {
  596.   int i, j, done = 0;                          /* lengths of line, code */
  597.   char ps1[] = ">>> ";
  598.   char ps2[] = "... ";
  599.   char *prompt = ps1;
  600.   char *msg, *line, *code = NULL;
  601.   PyObject *src, *glb, *loc;
  602.   PyObject *exc, *val, *trb, *obj, *dum;
  603.  
  604.   Py_Initialize ();
  605.   loc = PyDict_New ();
  606.   glb = PyDict_New ();
  607.   PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
  608.  
  609.   while (!done)
  610.   {
  611.     line = readline (prompt);
  612.  
  613.     if (NULL == line)                          /* CTRL-D pressed */
  614.     {
  615.       done = 1;
  616.     }
  617.     else
  618.     {
  619.       i = strlen (line);
  620.  
  621.       if (i > 0)
  622.         add_history (line);                    /* save non-empty lines */
  623.  
  624.       if (NULL == code)                        /* nothing in code yet */
  625.         j = 0;
  626.       else
  627.         j = strlen (code);
  628.  
  629.       code = realloc (code, i + j + 2);
  630.       if (NULL == code)                        /* out of memory */
  631.         exit (1);
  632.  
  633.       if (0 == j)                              /* code was empty, so */
  634.         code[0] = '\0';                        /* keep strncat happy */
  635.  
  636.       strncat (code, line, i);                 /* append line to code */
  637.       code[i + j] = '\n';                      /* append '\n' to code */
  638.       code[i + j + 1] = '\0';
  639.  
  640.       src = Py_CompileString (code, "<stdin>", Py_single_input);
  641.  
  642.       if (NULL != src)                         /* compiled just fine - */
  643.       {
  644.         if (ps1  == prompt ||                  /* ">>> " or */
  645.             '\n' == code[i + j - 1])           /* "... " and double '\n' */
  646.         {                                               /* so execute it */
  647.           dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
  648.           Py_XDECREF (dum);
  649.           Py_XDECREF (src);
  650.           free (code);
  651.           code = NULL;
  652.           if (PyErr_Occurred ())
  653.             PyErr_Print ();
  654.           prompt = ps1;
  655.         }
  656.       }                                        /* syntax error or E_EOF? */
  657.       else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
  658.       {
  659.         PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */
  660.  
  661.         if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
  662.             !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
  663.         {
  664.           Py_XDECREF (exc);
  665.           Py_XDECREF (val);
  666.           Py_XDECREF (trb);
  667.           prompt = ps2;
  668.         }
  669.         else                                   /* some other syntax error */
  670.         {
  671.           PyErr_Restore (exc, val, trb);
  672.           PyErr_Print ();
  673.           free (code);
  674.           code = NULL;
  675.           prompt = ps1;
  676.         }
  677.       }
  678.       else                                     /* some non-syntax error */
  679.       {
  680.         PyErr_Print ();
  681.         free (code);
  682.         code = NULL;
  683.         prompt = ps1;
  684.       }
  685.  
  686.       free (line);
  687.     }
  688.   }
  689.  
  690.   Py_XDECREF(glb);
  691.   Py_XDECREF(loc);
  692.   Py_Finalize();
  693.   exit(0);
  694. }
  695. </pre>
  696. </div>
  697. <div class="section" id="how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">
  698. <h1><a class="toc-backref" href="#id23">17   How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></h1>
  699. <p>To dynamically load g++ extension modules, you must recompile Python, relink it using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o").</p>
  700. </div>
  701. <div class="section" id="can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">
  702. <h1><a class="toc-backref" href="#id24">18   Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></h1>
  703. <p>In Python 2.2, you can inherit from builtin classes such as int, list, dict, etc.</p>
  704. <p>The Boost Python Library (BPL, <a class="reference external" href="http://www.boost.org/libs/python/doc/index.html">http://www.boost.org/libs/python/doc/index.html</a>)
  705. provides a way of doing this from C++ (i.e. you can inherit from an
  706. extension class written in C++ using the BPL).</p>
  707. </div>
  708. <div class="section" id="when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2">
  709. <h1><a class="toc-backref" href="#id25">19   When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"?</a></h1>
  710. <p>You are using a version of Python that uses a 4-byte representation
  711. for Unicode characters, but some C extension module you are importing
  712. was compiled using a Python that uses a 2-byte representation for
  713. Unicode characters (the default).</p>
  714. <p>If instead the name of the undefined symbol starts with
  715. <tt class="docutils literal"><span class="pre">PyUnicodeUCS4</span></tt>, the problem is the reverse: Python was built using
  716. 2-byte Unicode characters, and the extension module was compiled using
  717. a Python with 4-byte Unicode characters.</p>
  718. <p>This can easily occur when using pre-built extension packages.  RedHat
  719. Linux 7.x, in particular, provided a "python2" binary that is compiled
  720. with 4-byte Unicode.  This only causes the link failure if the extension
  721. uses any of the <tt class="docutils literal"><span class="pre">PyUnicode_*()</span></tt> functions.  It is also a problem if an
  722. extension uses any of the Unicode-related format specifiers for
  723. <tt class="docutils literal"><span class="pre">Py_BuildValue</span></tt> (or similar) or parameter specifications for
  724. <tt class="docutils literal"><span class="pre">PyArg_ParseTuple()</span></tt>.</p>
  725. <p>You can check the size of the Unicode character a Python interpreter is
  726. using by checking the value of sys.maxunicode:</p>
  727. <pre class="literal-block">
  728. >>> import sys
  729. >>> if sys.maxunicode > 65535:
  730. ...     print 'UCS4 build'
  731. ... else:
  732. ...     print 'UCS2 build'
  733. </pre>
  734. <p>The only way to solve this problem is to use extension modules compiled
  735. with a Python binary built using the same size for Unicode characters.</p>
  736. </div>
  737. </div>
  738. </body>
  739. </html>
  740.